<script setup lang="ts">

import {
  QueryType,
  ReservationType,
  type TableData,
  type AnyData,
  type ReservationData
} from "../../../types/DataTypes.ts";
import {Edit, Ticket, CloseBold} from "@element-plus/icons-vue";
import {computed, watch, inject, ref} from "vue";
import { api } from "../../../api/Api.ts"
import {DataKey, type DataKeyType} from "../../../types/KeyTypes.ts";
import {useAuthStore} from "../../../stores/authStore.ts";

const authStore = useAuthStore();
const props = defineProps<{
  queryType: QueryType,
  data: TableData,
  loading: boolean,
  showResults: boolean,
}>()

const emit = defineEmits<{
  'edit': [boolean, AnyData]
  'reservation': [boolean, AnyData]
}>()

const currentPage = ref(1)
const pageSize = ref(5)
watch(()=>props.queryType, ()=>{
  currentPage.value = 1;
})
const paginatedData = computed(()=>{
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  switch (props.queryType){
    case QueryType.BusQuery: return props.data.busData.slice(start,end);
    case QueryType.FlightQuery: return props.data.flightData.slice(start,end);
    case QueryType.HotelQuery: return props.data.hotelData.slice(start,end);
    case QueryType.CustomersQuery: return props.data.customerData.slice(start,end);
    case QueryType.ReservationQuery: return props.data.reservationData.slice(start,end);
  }
});

const handleEdit = (rowData : AnyData) => {
  emit('edit',true,rowData);
}

const handleReservation = (rowData : AnyData) => {
  emit('reservation',true,rowData)
}
const {isNeedUpdate} = inject<DataKeyType>(DataKey) as DataKeyType;
// 处理取消预约
const handleCancelReservation = async (reservation: ReservationData) => {
  if(!reservation) return;
  try {
    // 确认对话框
    await ElMessageBox.confirm(
        `确定要取消 ${reservation.customerName} 的${ReservationType.getTypeName(reservation.reservationType)}预约${reservation.reservationKey}吗？`,
        '取消预约确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    // 调用API取消预约
    const response = await api.reservation.cancelReservation(reservation.reservationKey);

    if (response.success) {
      ElMessage.success('预约取消成功');
      // 让父组件重新获取数据
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '取消预约失败');
    }
  } catch (error: any) {
    if (error === 'cancel') {
      // 用户点击了取消
      ElMessage.info('已取消操作');
    } else {
      // 其他错误
      console.error('取消预约失败:', error);
      ElMessage.error(error.response?.data?.message || '取消预约失败，请重试');
    }
  } finally {
  }
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
}

// 获取预订类型标签样式
const getReservationTagType = (type:number) => {
  switch(type) {
    case 1: return 'primary';
    case 2: return 'success';
    case 3: return 'warning';
    default: return 'info';
  }
};

</script>

<template>
  <!-- 查询结果展示区域 -->
  <div class="query-results" v-if="showResults">
    <!--      显示航班-->
    <template v-if="queryType===QueryType.FlightQuery && data.flightData.length>0">

      <div class="results-header">
        <h3>查询结果</h3>
      </div>

      <el-table :data="paginatedData" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="flightNum" label="航班号" width="100" />
        <el-table-column prop="fromCity" label="出发地" width="80" />
        <el-table-column prop="arivCity" label="目的地" width="80" />
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.availSeat>0 ? 'success' : 'danger'">
              {{ scope.row.availSeat>0 ? '有座' : '售空' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="availSeat" label="座位剩余" width="80" />
        <el-table-column prop="totalSeat" label="座位总数" min-width="80" />
        <el-table-column prop="price" label="价格" min-width="80" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default = "scope">
            <el-button
                size="large"
                type="primary"
                link
                :icon="Edit"
                v-if="authStore.getCustomerName==='admin'"
                @click="handleEdit(scope.row as AnyData)"
            >
              编辑
            </el-button>
            <el-button
                size="large"
                type="primary"
                link
                :icon="Ticket"
                @click="handleReservation(scope.row as AnyData)"
                :disabled="scope.row.availSeat <= 0">
              预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            :page-size="pageSize"
            :current-page="currentPage"
            layout="total, prev, pager, next, jumper"
            :total="data?.flightData.length"
            @current-change="handlePageChange"
        />
      </div>
    </template>

    <!--      显示巴士-->
    <template v-if="queryType===QueryType.BusQuery && data.busData.length>0">

      <div class="results-header">
        <h3>查询结果</h3>
      </div>

      <el-table :data="paginatedData" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="location" label="所在地" width="80" />
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.availBus>0 ? 'success' : 'danger'">
              {{ scope.row.availBus>0 ? '有车' : '售空' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="availBus" label="巴士剩余" width="80" />
        <el-table-column prop="totalBus" label="巴士总数" min-width="80" />
        <el-table-column prop="price" label="价格" min-width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default = "scope">
            <el-button
                size="large"
                type="primary"
                link
                :icon="Edit"
                @click="handleEdit(scope.row as AnyData)"
                v-if="authStore.getCustomerName==='admin'"
            >
              编辑
            </el-button>
            <el-button
                size="large"
                type="primary"
                link
                :icon="Ticket"
                @click="handleReservation(scope.row as AnyData)"
                :disabled="scope.row.availBus <= 0">
              预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>



      <div class="pagination-container">
        <el-pagination
            :page-size="pageSize"
            :current-page="currentPage"
            layout="total, prev, pager, next, jumper"
            :total="data?.busData.length"
            @current-change="handlePageChange"
        />
      </div>
    </template>
    <!--      显示酒店-->
    <template v-if="queryType===QueryType.HotelQuery && data.hotelData.length>0">

      <div class="results-header">
        <h3>查询结果</h3>
      </div>

      <el-table :data="paginatedData" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="location" label="所在地" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.availRoom>0 ? 'success' : 'danger'">
              {{ scope.row.availRoom>0 ? '有房' : '售空' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="availRoom" label="房间剩余" width="80" />
        <el-table-column prop="totalRoom" label="房间总数" min-width="80" />
        <el-table-column prop="price" label="价格" min-width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default = "scope">
            <el-button
                size="large"
                type="primary"
                link
                :icon="Edit"
                @click="handleEdit(scope.row as AnyData)"
                v-if="authStore.getCustomerName==='admin'"
            >
              编辑
            </el-button>
            <el-button
                size="large"
                type="primary"
                link
                :icon="Ticket"
                @click="handleReservation(scope.row as AnyData)"
                :disabled="scope.row.availRoom <= 0">
              预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            :page-size="pageSize"
            :current-page="currentPage"
            layout="total, prev, pager, next, jumper"
            :total="data?.hotelData.length"
            @current-change="handlePageChange"
        />
      </div>
    </template>
    <!--      显示用户-->
    <template v-if="queryType===QueryType.CustomersQuery && data.customerData.length>0">

      <div class="results-header">
        <h3>查询结果</h3>
      </div>

      <el-table :data="paginatedData" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="customerName" label="用户名" width="200"/>
        <el-table-column prop="customerId" label="用户ID" width="200"/>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
                size="large"
                type="primary"
                link
                :icon="Edit"
                @click="handleEdit(scope.row as AnyData)"
                v-if="authStore.getCustomerName==='admin'"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            :page-size="pageSize"
            :current-page="currentPage"
            layout="total, prev, pager, next, jumper"
            :total="data?.customerData.length"
            @current-change="handlePageChange"
        />
      </div>
    </template>
    <!--      显示预约-->
    <template v-if="queryType===QueryType.ReservationQuery && data.reservationData.length>0">

      <div class="results-header">
        <h3>查询结果</h3>
      </div>

      <el-table :data="paginatedData" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="customerName" label="用户名" width="100" />
        <el-table-column prop="reservationType" label="预约类型" min-width="100">
          <template #default="scope">
            <el-tag :type="getReservationTagType(scope.row.reservationType)">
              {{ ReservationType.getTypeName(scope.row.reservationType) }}
            </el-tag>
          </template>
        </el-table-column>
<!--        TODO: 提供信息预览      -->
        <el-table-column prop="reservationKey" label="预约码" width="200" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
                size="large"
                type="danger"
                link
                :icon="CloseBold"
                @click="handleCancelReservation(scope.row as ReservationData)"
            >
              取消预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            :page-size="pageSize"
            :current-page="currentPage"
            layout="total, prev, pager, next, jumper"
            :total="data?.reservationData.length"
            @current-change="handlePageChange"
        />
      </div>
    </template>

  </div>
</template>

<style scoped>
.query-results {
  margin-top: 30px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.results-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.total-count {
  color: #606266;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}
</style>